package com.xingyang.controller;

import com.google.code.kaptcha.Producer;
import com.xingyang.controller.request.SendCodeRequest;
import com.xingyang.enums.BizCodeEnum;
import com.xingyang.enums.SendCodeEnum;
import com.xingyang.service.NotifyService;
import com.xingyang.utils.CommonUtil;
import com.xingyang.utils.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 著名信仰,愿景：让技术不再难学
 **/

@RestController
@Slf4j
@RequestMapping("/api/notify/v1")
public class NotifyController {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /*/临时使用10分钟有效，方便测试
     */
    private static final long CAPTCHA_CODE_EXPIRED = 60 * 1000 * 10;





    @GetMapping("captcha")
    public void  getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String text = captchaProducer.createText();
        log.info("验证码内容{}",text );

        redisTemplate.opsForValue().set(getCaptchaKey(request),text,CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);

        BufferedImage image = captchaProducer.createImage(text);
        try ( ServletOutputStream outputStream = response.getOutputStream()){

            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();

        } catch (IOException e) {
//            throw new RuntimeException(e);
            log.info("获取刘失败");
        }

    }


    private String getCaptchaKey(HttpServletRequest request){
        String ipAddr = CommonUtil.getIpAddr(request);

        String header = request.getHeader("User-Agent");

        String key="account-service:captcha:"+CommonUtil.MD5(ipAddr+header);

        log.info("验证码key:{}",key);
        return key;
    }

    /*
    * 发送短信验证码
    * */
    @PostMapping("send_code")
    public JsonData sendCode(@RequestBody SendCodeRequest sendCodeRequest,HttpServletRequest request){


        String key=getCaptchaKey(request);
        String cacheCaptcha = redisTemplate.opsForValue().get(key);
        String captcha=sendCodeRequest.captcha;

        if (cacheCaptcha!=null&&captcha!=null &&cacheCaptcha.equalsIgnoreCase(captcha)){
            //删除成功
            redisTemplate.delete(key);
         JsonData jsonData=   notifyService.sendCode(SendCodeEnum.USER_REGISTER,sendCodeRequest.getTo());
         return jsonData;

        }else {

            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
        }

    }

}
